import store from '@/store'
import { loginAuthList } from '@/config'
import { spliceCommonAgrs } from '@/utils'

function login (redirectUri) {
	uni.navigateTo({
		url: `/pages/login/index?redirectUri=${encodeURIComponent(redirectUri)}`
	})
}

uni.addInterceptor('navigateTo', {
	invoke (args) {
		// #ifdef WEB
		args.url = spliceCommonAgrs(args.url)
		// #endif
		if (loginAuthList.includes(args.url.replace(/\?[\s\S]*/, ''))) {
			if (!store.state.user.userInfo.token || !store.state.user.isValidloginState) {
				if (store.state.user.userInfo.token) {
					uni.showLoading({
						title: '',
						mask: true
					})
					store.dispatch('user/checkLoginStatus').then(([res]) => {
						uni.hideLoading()
						if (Number(res._data?.status) === 1) {
							uni.navigateTo({
								url: args.url
							})
						} else {
							login(args.url)
						}
					}).catch(err => {
						uni.hideLoading()
						login(args.url)
					})
				} else {
					login(args.url)
				}
				return false
			}
		}
	}
})